﻿using System.Collections.Generic;
using UnityEngine;


public enum XEffectLineMode
{
    None,
    Sequence,
}

public class XEffectLineRender : MonoBehaviour
{
    [HideInInspector]
    public int gid = 0;

    public XEffectLineMode mode;
    public bool autoDestroy=true;
    
    /// <summary>
    /// 
    /// </summary>
    private LineRenderer line;
    private List<Transform> targets = new List<Transform>();
    private float duration = 0;
    private float time = 0;
    private int old = 0;
    private int cur = 1;
    private bool fire = false;

    private void Awake()
    {
        line = GetComponent<LineRenderer>();
        if (!line)
            throw new System.NullReferenceException();
    }

    private void Update()
    {
        if (!fire || targets.Count < 2)
            return;

        if (mode == XEffectLineMode.Sequence)
        {
            duration -= Time.deltaTime;
            if (duration <= 0)
            {
                duration = time;

                int old = this.cur;
                int cur = this.cur + 1;

                if (cur < targets.Count)
                {
                    line.SetPosition(0, targets[old].position);
                    line.SetPosition(1, targets[cur].position);

                    this.cur = cur;
                }
                else
                {
                    if (autoDestroy)
                    {
                        Destroy(gameObject);
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < targets.Count; i++)
            {
                if (!targets[i])
                {
                    targets.RemoveAt(i);
                    break;
                }

                line.SetPosition(i, targets[i].position);
            }

            duration -= Time.deltaTime;
            if (duration <= 0 && autoDestroy)
            {
                Destroy(gameObject);
            }
        }
    }

    public void Fire(Transform[] targtes, float time, XEffectLineMode lineMode)
    {
        targets.Clear();
        foreach (Transform trans in targtes)
        {
            targets.Add(trans);
        }
        
        this.time = time;
        duration = time;
        fire = true;

        mode = lineMode;
        switch (mode)
        {
            case XEffectLineMode.None:
                line.positionCount = targtes.Length;
                for (int i = 0; i < targtes.Length; i++)
                {
                    line.SetPosition(i, targtes[i].position);
                }
                break;

            case XEffectLineMode.Sequence:
                line.SetPosition(old, targtes[old].position);
                line.SetPosition(cur, targtes[cur].position);
                break;
        }
    }
}
